
import xlwt
import xlrd
import datetime
import json
import tempfile
import os
import io
from apps.pay.order.dao import OrderDao


# 导出表格
def exportExcelForWxForExpressage(fp):
    # 保存文件到临时文件
    with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(fp.name)[1]) as temp_file:
        for chunk in fp.chunks():
            temp_file.write(chunk)
        temp_file_path = temp_file.name
    
    try:
        # 打开Excel文件
        workbook = xlrd.open_workbook(temp_file_path)
        # 获取第一个工作表
        worksheet = workbook.sheet_by_index(0)
        # 获取表头
        headers = []
        for col in range(worksheet.ncols):
            value = worksheet.cell_value(0, col)
            headers.append(value)
        # 存储所有行数据
        data = []
        
        # 遍历每一行
        for row in range(1, worksheet.nrows):
            row_data = {}
            for col in range(worksheet.ncols):
                row_data[headers[col]] = worksheet.cell_value(row, col)
            
            row_data['发货模式'] = '统一发货'
            _order = OrderDao().findOneByOrderId(row_data.get('商户单号'))
            if _order.scene == 'generay' or _order.scene == 'giftSection':
                row_data['发货方式'] = '物流快递'
                expressageinfos = []
                _subOrders = OrderDao().findAllSubOrder().filter(order=_order)
                if _subOrders.count()>0:
                    for _subOrder in _subOrders:
                        if _subOrder.expressageinfo:
                            expressageinfo = json.loads(_subOrder.expressageinfo)
                            expressageinfos.append(expressageinfo)
                if len(expressageinfos)>0:
                    row_data['快递公司'] = expressageinfos[0].get('expressageCompany')
                    row_data['快递单号'] = expressageinfos[0].get('expressageNum')
                else:
                    continue
            elif _order.scene == 'recharge' or _order.scene == 'payForFranchisee':
                row_data['发货方式'] = '用户自提'
            else:
                row_data['发货方式'] = '用户自提'
 
            if _order.content and json.loads(_order.content).get('orderItemList') and len(json.loads(_order.content).get('orderItemList'))>0:
                item = json.loads(_order.content).get('orderItemList')[0]
                row_data['商品信息'] = item.get('itemName')
            else:
                row_data['商品信息'] = '鑫珑名品特殊商品'
            data.append(row_data)
    except Exception as e:
        print('导入失败', e)
    
    # 导出批量发货模版
    workbook = xlwt.Workbook(encoding = 'utf-8')
    worksheet = workbook.add_sheet('批量发货模版')

    style = xlwt.XFStyle()
    #设置样式
    alignment = xlwt.Alignment()
    # 水平位置：0x01(左端对齐)、0x02(水平方向上居中对齐)、0x03(右端对齐)
    alignment.horz = 0x01
    # 垂直方向：0x00(上端对齐)、 0x01(垂直方向上居中对齐)、0x02(底端对齐)
    alignment.vert = 0x01
    style.alignment = alignment
    #设置字体
    font = xlwt.Font()
    # font.bold = True
    style.font = font

    row_first = ['商户单号', '交易单号', '发货方式', '发货模式', '快递公司','快递单号','商品信息']
    # 设置第一行
    for col_index, title in enumerate(row_first):
        style1 = xlwt.XFStyle()
        font1 = xlwt.Font()
        font1.bold = True
        style1.font = font1
        worksheet.write(0, col_index, title, style1)

    row_index = 1
    for row_i, record in enumerate(data):
        last_col_index = 0
        for col_index, title in enumerate(row_first):
            if title == '商户单号':
                worksheet.write(row_index, col_index, record.get(title), style)
                worksheet.col(col_index).width = 6000
            if title == '交易单号':
                worksheet.write(row_index, col_index, record.get(title), style)
                worksheet.col(col_index).width = 6000
            if title == '发货方式':
                worksheet.write(row_index, col_index, record.get(title), style)
                worksheet.col(col_index).width = 6000
            if title == '发货模式':
                worksheet.write(row_index, col_index, record.get(title), style)
                worksheet.col(col_index).width = 6000
            if title == '快递公司':
                worksheet.write(row_index, col_index, record.get(title), style)
                worksheet.col(col_index).width = 6000
            if title == '快递单号':
                worksheet.write(row_index, col_index, record.get(title), style)
                worksheet.col(col_index).width = 6000
            if title == '商品信息':
                worksheet.write(row_index, col_index, record.get(title), style)
                worksheet.col(col_index).width = 6000
                last_col_index = col_index
        row_index = row_index+1
    output = io.BytesIO()
    workbook.save(output)
    output.seek(0)
    return output